package com.cmc.cloud.cmclink.doc.controller.admin.multimodaltransport;

import com.cmc.cloud.cmclink.doc.api.document.emums.ExImTypeEnum;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.rpcservice.CustomerRpcService;
import com.cmc.cloud.cmclink.doc.vo.multimodaltransport.multiagentinfo.*;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.excel.core.util.ExcelUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.servlet.http.HttpServletResponse;
import javax.validation.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;


import com.cmc.cloud.cmclink.doc.entity.MultiAgentInfoDO;
import com.cmc.cloud.cmclink.doc.convert.MultiAgentInfoConvert;
import com.cmc.cloud.cmclink.doc.service.MultiAgentInfoService;


/**
 * 多式联运代理信息维护前端接口Controller
 * 
 * @author codegen
 */
@Tag(name = "管理后台 - 多式联运代理信息维护")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL +"/multi-agent-info")
public class MultiAgentInfoController {

    @Resource
    private MultiAgentInfoService multiAgentInfoService;
    @Resource
    private CustomerRpcService nameTransferService;

    @Operation(summary = "创建多式联运代理信息维护")
	@PostMapping("/create")
    @PreAuthorize("@ss.hasPermission('doc:agentInformation:add')")
    public CommonResult<Void> createMultiAgentInfo(@Valid @RequestBody MultiAgentInfoCreateReqVO createReqVO) {
        multiAgentInfoService.createMultiAgentInfo(createReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新多式联运代理信息维护")
	@PostMapping("/update")
    @PreAuthorize("@ss.hasPermission({'doc:agentInformation:edit','doc:agentInformation:on'})")
    public CommonResult<Void> updateMultiAgentInfo(@Valid @RequestBody MultiAgentInfoUpdateReqVO updateReqVO) {
        multiAgentInfoService.updateMultiAgentInfo(updateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "删除多式联运代理信息维护")
	@PostMapping("/delete/{ids}")
    @Parameter(name = "ids", description = "编号 逗号,分隔", required = true)
    @PreAuthorize("@ss.hasPermission('doc:agentInformation:delete')")
    public CommonResult<Void> deleteMultiAgentInfo(@PathVariable("ids") String ids) {
        multiAgentInfoService.deleteMultiAgentInfo(ids);
        return CommonResult.success();
    }

    /**
     * 获得多式联运代理信息维护
     * @param id
     * @return
     */
    @Operation(summary = "获得多式联运代理信息维护")
	@GetMapping("/get/{id}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('doc:multi-agent-info:query')")
    public CommonResult<MultiAgentInfoRespVO> getMultiAgentInfo(@PathVariable("id") Long id) {
        MultiAgentInfoDO multiAgentInfo = multiAgentInfoService.getMultiAgentInfo(id);
        return CommonResult.success(MultiAgentInfoConvert.INSTANCE.convert(multiAgentInfo));
    }


    @Operation(summary = "获得多式联运代理信息维护分页")
	@PostMapping("/page")
    @UseResponsePropertyAdvice
    @PreAuthorize("@ss.hasPermission('doc:agentInformation:search')")
    public CommonResult<PageResult<MultiAgentInfoRespVO>> getMultiAgentInfoPage(@Valid  @RequestBody MultiAgentInfoPageReqVO pageVO) {
        PageResult<MultiAgentInfoDO> pageResult = multiAgentInfoService.getMultiAgentInfoPage(pageVO);
        List<MultiAgentInfoRespVO> results = MultiAgentInfoConvert.INSTANCE.convertList(pageResult.getList());
        nameTransferService.fillCompanyNameByBkpCodeFunctionally(
                results,
                // 提取bkpCode的函数
                MultiAgentInfoRespVO::getAgentCode,
                // 设置本地名称的函数
                MultiAgentInfoRespVO::setCompanyNameLocal,
                // 设置英文名称的函数
                MultiAgentInfoRespVO::setCompanyNameEn
        );
        return CommonResult.success(new PageResult<>(results,pageResult.getTotal()));
    }

    @GetMapping("/excel-export")
    @Operation(summary = "excel导出")
    @Parameter(name = "polCode", description = "装货港代码")
    @Parameter(name = "podCode", description = "卸货港代码")
    @Parameter(name = "agentCode", description = "代理代码 同csm_code 公司客商主数据代码")
    @Parameter(name = "agentType")
    @Parameter(name = "exImType", description = "进出口类型")
    @PreAuthorize("@ss.hasPermission('doc:agentInformation:export')")
    public void exportExcel(HttpServletResponse response
            , @RequestParam(value = "polCode", required = true) String polCode
            , @RequestParam(value = "podCode", required = true) String podCode
            , @RequestParam(value = "agentCode", required = false) String agentCode
            , @RequestParam(value = "agentType", required = false) String agentType
            , @RequestParam(value = "exImType",required = false) String exImType) throws IOException {
        MultiAgentInfoPageReqVO reqVO = new MultiAgentInfoPageReqVO();
        reqVO.setPolCode(polCode);
        reqVO.setPodCode(podCode);
        reqVO.setAgentCode(agentCode);
        reqVO.setAgentType(agentType);
        reqVO.setImExType(exImType);
        List<MultiAgentInfoDO> exportList = multiAgentInfoService.exportExcel(reqVO);
        List<MultiAgentInfoExcelRespVO> results = MultiAgentInfoConvert.INSTANCE.convertListExcel(exportList);
        List<MultiAgentInfoExcelRespVO> resultsN  = results.stream().peek(vo->{
            if(ExImTypeEnum.EX.getValue().equals(exImType)){
                vo.setPortCode(vo.getPodCode());
            }
            if(ExImTypeEnum.IM.getValue().equals(exImType)){
                vo.setPortCode(vo.getPolCode());
            }
        }).collect(Collectors.toList());
        nameTransferService.fillCompanyNameByBkpCodeFunctionally(
                resultsN,
                // 提取bkpCode的函数
                MultiAgentInfoExcelRespVO::getAgentCode,
                // 设置本地名称的函数
                MultiAgentInfoExcelRespVO::setCompanyNameLocal,
                // 设置英文名称的函数
                MultiAgentInfoExcelRespVO::setCompanyNameEn
        );
        // FIXME 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("multiAgentInfo.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "multiAgentInfo.xls", "multiAgentInfo", MultiAgentInfoExcelRespVO.class, resultsN);
    }
}
